package com.magic233.service;

import com.magic233.mapper.LogsMapper;
import com.magic233.utils.SMSTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: CodeServiceImpl
 * Description:
 * date: 2021/5/29 21:26
 * author: zouyuan
 */
@Service
public class CodeServiceImpl implements CodeService {
    @Autowired
    private LogsService logsService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public int sendCode(String phone) {
//        调用阿里云
        long code = SMSTools.sendCode(phone);
//        long code = (long) (Math.random() * (999999 - 100000) + 100000);
        if (code != 0) {
            //发送成功
            //将验证码存入redis，五分钟有效
            redisTemplate.opsForValue().set(phone,String.valueOf(code),5, TimeUnit.MINUTES);

            String thing = "向" + phone + "发送了一条短信验证码";
            logsService.addLog(thing);
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public boolean verifyCode(String phone, String code) {
        String realCode = String.valueOf(redisTemplate.opsForValue().get(phone));
        System.out.println(realCode);
        if (code.equals(realCode)) {
            String string = phone + "验证码验证正确";
            logsService.addLog(string);
            return true;
        } else {
            String string = phone + "验证码验证错误";
            logsService.addLog(string);
            return false;
        }
    }
}
